/*
 * @Description:
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2023-08-07 07:51:26
 * @LastEditors: zss
 * @LastEditTime: 2024-10-11 17:08:09
 */
import { ifs, ts, Tsrv } from '@/services';
import { N_oFlowchart, N_oGraph, N_oInteraction, N_oSetupPanel } from '@/types';
import { N_openGraphData } from './openGraphData/types';

class T_cmd {
  // 主组件箱
  private compBox: ifs.I_compBox;

  // 主组件ID
  private compID: string;

  // 主组件实例
  private self: N_oGraph.oGraph;

  public tableName: string;

  public dbType: string;

  private _graphEditorState: string = 'none';

  // public editorState: 'new' | 'modify' | 'none' = 'none';

  // mongo 图数据
  public oldGraphRec: any;

  // 主单 数据
  public oldMainRec: any;

  // 当前父ID
  public currParentID: string;

  // 关联字段
  public associationField: string;

  // 节点栏位
  public nodeColumns: any;

  public tableColumns: any;

  // public tableColumnData: Set<ifs.I_fv> = new Set();
  // fieldName v
  public tableColumnData: Map<string, any> = new Map();

  // public nodeColumnData: Set<ifs.I_fv> = new Set();
  // fieldName v
  public nodeColumnData: Map<string, Array<ifs.I_fv>> = new Map();

  private oOpenGraphData: N_openGraphData.openGraphData = null;

  public searchEventMsg: any = null;

  private TCoordination: ifs.I_compCoordination = null;

  private toolbarStatusBak: any = null;

  // 字段搜索过滤条件
  private fieldsSearchFilter: Map<string, Array<() => void>> = new Map();

  public set graphEditorState(p: string) {
    this._graphEditorState = p;
    this.self.nodeAttrDisabled = p === 'none';
    this.self.nodeAttrLabelDisabled = p === 'none';
    if (p === 'new') {
      this.oldGraphRec = null;
      this.oldMainRec = null;
    }
  }

  public get graphEditorState(): string {
    return this._graphEditorState;
  }

  // 主组件created里初始化
  public init(self: any, compBoxInfo: ifs.I_compBoxInfo) {
    this.self = self;
    this.compBox = compBoxInfo.TcompBox;
    this.compID = compBoxInfo.compID;
  }

  public openData() {
    if (this.oOpenGraphData === null) {
      this.oOpenGraphData = this.compBox.getCompMergeName(
        this.compID,
        'oOpenGraphData'
      );
    }
    this.oOpenGraphData.setDisplay(true);
  }

  public doSave(e: N_oFlowchart.I_toolbarClick): Promise<boolean> {
    return new Promise(resolve => {
      if (this.graphEditorState === 'new') {
        this.newData(e.e).then(b => {
          resolve(b);
        });
      } else if (this.graphEditorState === 'modify') {
        this.changeData(e.e).then(b => {
          resolve(b);
        });
      } else {
        resolve(false);
      }
    });
  }

  private async newData(d: any): Promise<boolean> {
    try {
      const [b, res, msg] = await Tsrv.addBill(await this.getAddBillParams(d));
      this.self.$msg(msg ?? res.msg);
      if (res.success) {
        return true;
      }
      return false;
    } catch (err) {
      this.self.$msg(err);
      throw new Error(err);
    }
  }

  private async getAddBillParams(d: any): Promise<ifs.I_addbpaArg> {
    const id = await Tsrv.getSnowIDFmtStr();
    const p = new ts.T_addbpaArg();
    const headIns = new ts.T_bpaHeadInsRec();
    const graphData = Tsrv.utils.clone(d, true);
    delete graphData.key;
    const md5Code = Tsrv.utils.md5(JSON.stringify(graphData));
    const bodyIns = new ts.T_bpaBodyInsRec();
    const bodyBaseData = new ts.T_baseData();
    const bodyRowData: Array<ifs.I_fv> = [];
    headIns
      .setFileInfo({})
      .setDataRule({} as ifs.I_rule)
      .setRowData(
        { field: 'id', value: id } as ifs.I_fv,
        { field: this.associationField, value: this.currParentID } as ifs.I_fv
        // ...Array.from(this.tableColumnData)
      );
    this.tableColumnData.forEach((v, k) => {
      const eFs = k.split('|');
      const isM2oOrSlc =
        (eFs.length === 4 && eFs[0] === 'm2o') ||
        (eFs.length === 3 && eFs[0] === 'slc');
      if (!isM2oOrSlc) {
        headIns.setRowData({ field: k, value: v } as ifs.I_fv);
      }
    });

    // 加入 ctd操作 前后事件
    const syncData = { insertRecords: headIns.rowData };
    const params = {
      funName: this.tableName,
      from: '',
      data: syncData,
      parentID: this.currParentID
    };
    const actionCfg = this.self.getActionCfg();
    this._setSyncEvents(actionCfg, 'Insert', headIns, params);
    const bodyId = await Tsrv.getSnowIDFmtStr();
    bodyRowData.push(
      { field: 'id', value: bodyId } as ifs.I_fv,
      { field: 'source_table', value: this.tableName } as ifs.I_fv,
      { field: 'master_bill_id', value: id } as ifs.I_fv,
      { field: 'data_type', value: 'g6' } as ifs.I_fv,
      { field: 'check_code', value: md5Code } as ifs.I_fv,
      { field: 'f_data', value: graphData } as ifs.I_fv,
      { field: 'db_type', value: 'mysql' } as ifs.I_fv,
      { field: 'db_name', value: Tsrv.getSysDBName() } as ifs.I_fv
    );
    bodyBaseData
      .setDataRule({} as ifs.I_rule)
      .setFileInfo({})
      .setRowData(...bodyRowData);
    bodyIns
      .setScope({ field: 'master_bill_id', value: id })
      .setData(bodyBaseData);
    p.setHeadFunName(this.tableName)
      .setHeadDbType(this.dbType)
      .setHeadRule({} as ifs.I_rule)
      .setHeadInsRec(headIns)
      .setBodyRule({} as ifs.I_rule)
      .addBodyData(
        Tsrv.globalVar.tableName.MONGO_GRAPH,
        Tsrv.globalVar.dbType.MONGO,
        bodyIns
      )
      .addBodyData(
        Tsrv.globalVar.tableName.MYSQL_GRAPH,
        Tsrv.globalVar.dbType.MYSQL,
        bodyIns
      );
    return p;
  }

  private changeData(d: any): Promise<boolean> {
    return new Promise(resolve => {
      if (this.tableColumnData.size > 0) {
        const p = new ts.T_ctdUpdRec();

        const filter = { id: { $eq: this.oldMainRec['id'] ?? '-1' } };
        const ds: Array<ifs.I_fv> = [];
        // const obj: Record<string, any> = { id: this.oldMainRec['id'] ?? '-1' };

        this.tableColumnData.forEach((v, k) => {
          const eFs = k.split('|');
          const isM2oOrSlc =
            (eFs.length === 4 && eFs[0] === 'm2o') ||
            (eFs.length === 3 && eFs[0] === 'slc');
          if (!isM2oOrSlc) {
            ds.push({ field: k, value: v } as ifs.I_fv);
            // obj[k] = v;
          }
        });

        // 加入 ctd操作 前后事件
        const _ds = Tsrv.utils.clone(ds, true);
        _ds.push({
          field: 'id',
          value: this.oldMainRec['id'] ?? '-1'
        } as ifs.I_fv);
        const syncData = { updateRecords: _ds };
        const params = {
          funName: this.tableName,
          from: '',
          data: syncData,
          parentID: this.currParentID
        };
        const actionCfg = this.self.getActionCfg();
        this._setSyncEvents(actionCfg, 'Edit', p, params);
        p.setData(
          {},
          filter,
          {} as ifs.I_rule,
          // ...Array.from(this.tableColumnData)
          ...ds
        );
        Tsrv.updRows(
          this.tableName,
          Tsrv.globalVar.dbType.MYSQL,
          {} as ifs.I_rule,
          p
        )
          .then(([b, res, msg]) => {
            this.self.$msg(msg ?? res.msg);
            if (res.success) {
              resolve(true);
            } else {
              resolve(false);
            }
          })
          .catch(err => {
            this.self.$msg(err);
            throw new Error(err);
          });
      }
      const p = new ts.T_ctdUpdRec();
      // const filter = { id: { $eq: this.oldGraphRec['id'] ?? '-1' } };
      const filter = { id: { $eq: this.oldGraphRec?.id ?? '-1' } };
      const graphData = Tsrv.utils.clone(d, true);
      delete graphData.key;
      const md5Code = Tsrv.utils.md5(JSON.stringify(graphData));
      // if (md5Code === this.oldGraphRec['check_code']) {
      if (md5Code === this.oldGraphRec?.check_code) {
        resolve(true);
        return;
      }
      p.setData(
        {},
        filter,
        {} as ifs.I_rule,
        { field: 'f_data', value: graphData } as ifs.I_fv,
        { field: 'check_code', value: md5Code } as ifs.I_fv
      );

      // Tsrv.updRows(
      //   Tsrv.globalVar.tableName.MONGO_GRAPH,
      //   Tsrv.globalVar.dbType.MONGO,
      //   {} as ifs.I_rule,
      //   p
      // )
      //   .then(([b, res, msg]) => {
      //     this.self.$msg(msg ?? res.msg);
      //     if (res.success) {
      //       resolve(true);
      //     } else {
      //       resolve(false);
      //     }
      //   })
      //   .catch(err => {
      //     this.self.$msg(err);
      //     throw new Error(err);
      //   });
      Promise.all([
        Tsrv.updRows(
          Tsrv.globalVar.tableName.MONGO_GRAPH,
          Tsrv.globalVar.dbType.MONGO,
          {} as ifs.I_rule,
          p
        ),
        Tsrv.updRows(
          Tsrv.globalVar.tableName.MYSQL_GRAPH,
          Tsrv.globalVar.dbType.MYSQL,
          {} as ifs.I_rule,
          p
        )
      ])
        .then(resp => {
          let isOK: boolean = true;
          for (const r of resp) {
            const [b, res, msg] = r;
            this.self.$msg(msg ?? res.msg);
            if (!res.success) {
              isOK = false;
              break;
            }
          }
          resolve(isOK);
        })
        .catch(err => {
          this.self.$msg(err);
          throw new Error(err);
        });
    });
  }

  public loadData(msg: any) {
    this.searchEventMsg = msg;
    const gpd = new ts.T_getPartDataArg();
    gpd.setFilter({
      [this.associationField]: { $eq: this.currParentID ?? '-1' }
    });
    gpd.setFunName(this.tableName);
    gpd.setTableName(this.tableName);
    gpd.setDbType(this.dbType);
    gpd.setLang(this.self.$i18n.locale);
    gpd.setPage(1, 10);
    gpd.setRule({} as ifs.I_rule);
    this.self.refFlowchart.clearGraph();
    Tsrv.getData(gpd).then(([b, res, _, m]) => {
      if (!m || !res.success) {
        this.self.$msg(m ?? res.msg);
      }
      this.oldGraphRec = null;
      this.oldMainRec = null;
      this.tableColumnData.clear();
      this.nodeColumnData.clear();
      if (res.data.total > 0) {
        this.loadGraph({ row: res.data.rows[0] }).then(ok => {
          if (ok) {
            this.self.refFlowchart.setViewMode();
          }
        });
        const rec = Tsrv.utils.clone(res.data.rows[0], true);
        delete rec['_XID'];
        delete rec['_file_info_id_'];
        delete rec['_sort_'];
        this.oldMainRec = rec;
      } else {
        this.self.refFlowchart.setToolbarBtnsDisabled('edit', true);
        this.self.cleanSubCompData(null);
      }
    });
  }

  public getGraph(): any {
    return this.self.refFlowchart.GT_editor.getGraph();
  }

  public loadGraph(e: any): Promise<boolean> {
    return new Promise(resolve => {
      const gpfd = new ts.T_getPartDataArg();
      this.self.refFlowchart.initGraph();
      gpfd.setFilter({
        $and: [
          { source_table: { $eq: this.tableName } },
          { [this.associationField]: { $eq: e.row.id ?? '-1' } }
        ]
      });
      // 规定的表名  mongo xcsys._sys_grpah
      // gpfd.setFunName(Tsrv.globalVar.tableName.MONGO_GRAPH);
      // gpfd.setTableName(Tsrv.globalVar.tableName.MONGO_GRAPH);
      // gpfd.setDbType(Tsrv.globalVar.dbType.MONGO);
      // 改为mysql取数据
      gpfd.setFunName(Tsrv.globalVar.tableName.MYSQL_GRAPH);
      gpfd.setTableName(Tsrv.globalVar.tableName.MYSQL_GRAPH);
      gpfd.setDbType(Tsrv.globalVar.dbType.MYSQL);

      gpfd.setLang(this.self.$i18n.locale);
      gpfd.setPage(1, 10);
      gpfd.setRule({} as ifs.I_rule);
      this.self.refFlowchart.clearGraph();
      this.oldGraphRec = null;

      Tsrv.getData(gpfd).then(([b, res, _, m]) => {
        if (!m || !res.success) {
          this.self.$msg(m ?? res.msg);
          resolve(false);
          return;
        }
        if (res.data.total > 0) {
          const rec = Tsrv.utils.clone(res.data.rows[0], true);
          const graph =
            typeof rec['f_data'] === 'string'
              ? JSON.parse(rec['f_data'])
              : rec['f_data'];
          delete rec['_XID'];
          delete rec['_file_info_id_'];
          delete rec['_sort_'];
          this.oldGraphRec = rec;
          // 无节点数据清空子组件
          if (rec?.f_data) {
            if (JSON.parse(this.oldGraphRec?.f_data)?.nodes) {
              this.self.cleanSubCompData(null);
            }
          }
          this.self.refFlowchart.loadGraphData(graph, true);
          this.self.refFlowchart.autoZoom();
          this.self.refFlowchart.setToolbarBtnsDisabled('audit', e.row.enabled);
          this.self.refFlowchart.setToolbarBtnsDisabled(
            'unAudit',
            !e.row.enabled
          );
          this.self.refFlowchart.setToolbarBtnsDisabled('edit', e.row.enabled);
        } else {
          this.self.refFlowchart.setToolbarBtnsDisabled('edit', true);
          this.self.cleanSubCompData(null);
        }
      });
      // const graph = JSON.parse(e.row.content);
      // const rec = Tsrv.utils.clone(e.row, true);
      // delete rec['_XID'];
      // delete rec['_file_info_id_'];
      // delete rec['_sort_'];

      // this.oldGraphRec = rec;
      resolve(true);
    });
  }

  public setPermission(conf: any) {
    const toolBarPms = conf?.permission.filter(
      el => el.area === 'toolbar' || el.area === 'default'
    );
    for (const ele of toolBarPms) {
      if (ele?.data?.browse && ele.data.browse === 0) {
        this.self.refFlowchart.hideToolbar();
        break;
      }
      ele?.data?.audit === 0 && this.self.refFlowchart.hideToolbarItem('audit');
      ele?.data?.unaudit === 0 &&
        this.self.refFlowchart.hideToolbarItem('unaudit');
      ele?.data?.new === 0 && this.self.refFlowchart.hideToolbarItem('new');
      ele?.data?.edit === 0 && this.self.refFlowchart.hideToolbarItem('edit');
      ele?.data?.delete === 0 &&
        this.self.refFlowchart.hideToolbarItem('delete');
    }
  }

  public addNodeColumnData(nodeID: string, ...d: ifs.I_fv[]) {
    if (this.nodeColumnData.has(nodeID)) {
      this.nodeColumnData.get(nodeID).push(...d);
    } else {
      this.nodeColumnData.set(nodeID, d);
    }
  }

  public addTableColumnData(fieldName: string, value: any) {
    this.tableColumnData.set(fieldName, value);
  }

  // 字段值的过滤条件（m2o、slc字段的过滤）
  public setFieldsSearchFilter() {
    const actions: any = this.self.getActionCfg();
    if (actions?.searchFilter) {
      const params: any = {};
      params.from = 'searchFilter';
      this.doEvent(actions.searchFilter, params);
    }
  }

  // 会话消息 / 字段事件 处理 serviceData用于
  public interactionMsgHandle(msg: N_oInteraction.I_msg, serviceData?: any) {
    if (Tsrv.utils.noValue(msg)) {
      return;
    }
    const obj = new ts.T_interaction();
    const res = obj.parseMsg(msg);
    if (res.isErr()) {
      this.self.$msg(res.errmsg);
      throw new Error(res.errmsg);
    } else {
      const interactionCf = res.getReturnData('conf');
      // 处理 cmd
      switch (interactionCf.cmd) {
        // case N_oInteraction.V_cmd.FIELD_EVENT: {
        //   const { fieldData } = serviceData;
        //   this.handleFieldEvent(interactionCf, fieldData).then(r => {
        //     if (r && !Tsrv.utils.noValue(interactionCf['actions'])) {
        //       this.handleInteractionAcions(interactionCf['actions']);
        //     }
        //     if (r) {
        //       this.interactionEventHandle({}, msg?.next);
        //     }
        //   });
        //   break;
        // }
        // case N_oInteraction.V_cmd.JUMP_TO_FUN:
        //   this.handleJumpToFun(interactionCf).then(r => {
        //     if (r) {
        //       this.interactionEventHandle({}, msg?.next);
        //     }
        //   });
        //   break;
        // case N_oInteraction.V_cmd.EXECUTE_ACTIONS: // 执行组件动作
        //   this.handleFrontendActions(interactionCf).then(r => {
        //     if (r) {
        //       this.interactionEventHandle({}, msg?.next);
        //     }
        //   });
        //   break;
        case N_oInteraction.V_cmd.SEARCH_FILTER:
          this.setSearchFilter(interactionCf).then(r => {
            if (r) {
              this.interactionEventHandle({}, msg?.next);
            }
          });
          break;
        default:
          Tsrv.utils
            .createModal('oInteraction', interactionCf)
            .then(r => {
              this.interactionEventHandle({ resp: r }, msg.next);
            })
            .catch(e => {
              console.error(e);
              this.self.$msg(e);
            });
          break;
      }
    }
  }

  // 交互闭环
  interactionEventHandle(params: any, next: any = null) {
    if (Object.prototype.hasOwnProperty.call(params, 'resp')) {
      if (Tsrv.utils.noValue(params?.resp?.data))
        params.resp.data = this.getCurrentGraphData();
    } else {
      params.funName = this.self.funName;
      params.title = '';
      params.from = '';
      params.data = this.getCurrentGraphData();
    }
    if (
      !Tsrv.utils.noValue(next) &&
      ((next?.ok && next?.ok?.spName) || (next?.cancel && next?.cancel?.spName))
    ) {
      if (next?.ok && next?.ok?.spName) {
        if (Object.prototype.hasOwnProperty.call(params, 'resp')) {
          if (params?.resp?.action && params?.resp?.action === 'confirm')
            this.doEvent(next.ok.spName, params);
        } else {
          this.doEvent(next.ok.spName, params);
        }
      } else if (
        next?.cancel &&
        next?.cancel?.spName &&
        params?.resp?.action &&
        params?.resp?.action === 'cancel'
      ) {
        this.doEvent(next.ok.spName, params);
      }
      if (next?.ok && next?.ok?.actions) {
        if (Object.prototype.hasOwnProperty.call(params, 'resp')) {
          if (params?.resp?.action && params?.resp?.action === 'confirm')
            this.handleInteractionAcions(next.ok.actions, next.ok);
        } else {
          this.handleInteractionAcions(next.ok.actions, next.ok);
        }
      } else if (
        next?.cancel &&
        next?.cancel?.actions &&
        params?.resp?.action &&
        params?.resp?.action === 'cancel'
      ) {
        this.handleInteractionAcions(next.cancel.actions, next.cancel);
      }
    } else {
      // this.doEvent('_sys_interaction_default_resp', params);
    }
  }

  // 处理交互消息 确认/取消 后动作
  private handleInteractionAcions(actions: object, e?: any) {
    Object.keys(actions).forEach(key => {
      switch (key) {
        case 'events':
          if (
            !Tsrv.noValue(actions['events']) &&
            Array.isArray(actions['events'])
          ) {
            const events = actions['events'];
            events.forEach(event => {
              if (Tsrv.utils.isJSONString(event.params)) {
                event.params = JSON.parse(event.params);
              }
              Tsrv.reliablySendingBusEvent(
                event.name,
                this.self.$bus,
                10,
                100,
                event.params
              );
            });
          }
          break;
        default:
          break;
      }
    });
  }

  public doEvent(action: string, params: any, serviceData?: any) {
    return new Promise<boolean>((resove, reject) => {
      Tsrv.doEvent(
        action,
        Tsrv.getFunInfo(this.self.mainFunName) as ifs.I_funInfo,
        () => params
      )
        .then(r => {
          if (r.isErr()) {
            this.self.$msg(r.errmsg);
            resove(false);
          } else {
            const res = r.getReturnData('conf');
            if (Tsrv.utils.noValue(res)) {
              return;
            }
            if (res.res?.data?.openUrl && res.res.success) {
              Tsrv.reliablySendingBusEvent(
                'OPEN_URL',
                undefined,
                undefined,
                undefined,
                res.res.data.openUrl
              );
            }
            // 0 存储过程  1 逻辑服务 2 规则库 3 web请求 4 系统策略
            if (res.apiType <= 2 || res.apiType === 4) {
              // 会话处理
              this.interactionMsgHandle(res.res.data?.request, serviceData);
              // this.loadTableData();
            } else if (res.apiType === 3) {
              // 请求接口
              const p = {
                funName: this.self.funName,
                from: 'WebRequest',
                title: action,
                data: {
                  req: res['data'],
                  res: res.res[0].data
                }
              };
              this.doEvent(Tsrv.lexicon.globalVar.spName.webApiReq, p);
            }
            resove(true);
          }
        })
        .catch(err => {
          console.error(err);
          reject(false);
        });
    });
  }

  private setSearchFilter(obj: object): any {
    return new Promise((resolve, reject) => {
      Object.keys(obj).forEach(key => {
        if (key !== 'cmd') {
          this.fieldsSearchFilter.set(key, obj[key]);
        }
      });
      resolve(true);
    });
  }

  public getFieldFilter(type: string): any {
    return this.fieldsSearchFilter.get(type);
  }

  public getCurrentGraphData() {
    return { tableRow: this.oldMainRec, graphRow: this.oldGraphRec };
  }

  // // 处理组件协调
  // public receEventCoordination(
  //   m: N_oSetupPanel.N_comps.I_eventCoordinationMsg
  // ) {
  //   switch (m.action.toolbar) {
  //     case 'insert':
  //       this.setTempToolbarStatusDisabled();
  //       this.self.cleanSubCompData();
  //       break;
  //     case 'delete':
  //       this.self.cleanSubCompData();
  //       break;
  //     case 'unAudit':
  //       break;
  //     case 'edit':
  //       this.setTempToolbarStatusDisabled();
  //       break;
  //     case 'unEdit':
  //       this.setTempToolbarStatusUnDisabled();
  //       break;
  //     case 'save':
  //       this.setTempToolbarStatusUnDisabled();
  //       break;
  //     case 'audit':
  //       break;
  //     case 'refresh':
  //       this.setTempToolbarStatusUnDisabled();
  //       break;
  //     default:
  //       throw new Error(`无法识别的事件属性[${m.action.toolbar}]`);
  //   }
  // }

  // // 处理组件协调
  // public sendEventCoordination(
  //   type: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  // ) {
  //   const messageConf = this.self.config?.messageConfig;
  //   if (!messageConf) {
  //     throw new Error(`找不到事件相关设置`);
  //   }
  //   if (!messageConf?.eventGroup) {
  //     return;
  //   }
  //   const m: N_oSetupPanel.N_comps.I_eventCoordinationMsg = {
  //     type: 'coordination',
  //     fromComp: {
  //       funName: this.self.config.name,
  //       fromEvenID: messageConf.custDefListener.coordination
  //     },
  //     action: {
  //       toolbar: type
  //     }
  //   };
  //   Object.keys(messageConf.eventGroup).forEach(k => {
  //     const toID: string =
  //       messageConf.eventGroup[k].custDefListener.coordination;
  //     if (
  //       this.self.config.messageConfig.custDefListener.coordination !== toID
  //     ) {
  //       Tsrv.reliablySendingBusEvent( toID, this.self.$bus, null, null, m);
  //     }
  //   });
  // }
  // 构建组件协作处理类
  public newTcompCoordination(conf: any) {
    // 组件调度
    this.TCoordination = new ts.T_compCoordination(
      conf.name,
      conf.messageConfig,
      {
        setTempToolbarStatusDisabled: (
          p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
        ) => {
          this.setTempToolbarStatusDisabled(p);
        },
        setTempToolbarStatusUnDisabled: (
          p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
        ) => {
          this.setTempToolbarStatusUnDisabled(p);
        },
        cleanSubCompData: (
          p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
        ) => {
          this.self.cleanSubCompData(p);
        },
        setMask: (p: boolean) => {
          this.self.isMask = p;
        }
      }
    );
  }

  private setTempToolbarStatusDisabled(
    p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {
    this.self.refFlowchart.setToolbarViewMode();
  }

  private setTempToolbarStatusUnDisabled(
    p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {
    this.self.refFlowchart.setToolbarExitViewMode();
  }

  private _setSyncEvents(
    actionCfg: any,
    eventType: 'Insert' | 'Edit',
    target: any,
    params: any
  ) {
    const beforeEvent = `before${eventType}`;
    const afterEvent = `after${eventType}`;
    const setEventMethod =
      eventType === 'Insert'
        ? (target as ts.T_bpaHeadInsRec).setBefEvent.bind(target)
        : (target as ts.T_ctdUpdRec).setBefEvent.bind(target);

    if (actionCfg && actionCfg[beforeEvent]) {
      const syncParams = new ts.T_syncParams();
      const _params = Tsrv.utils.clone(params, true);
      _params.from = beforeEvent;
      syncParams
        .setApiName(actionCfg[beforeEvent])
        .setUserInfo(Tsrv.getUserInfo() as ifs.I_userInfo)
        .setFunInfo(Tsrv.getFunInfo(this.self.mainFunName))
        .setSyncData(_params);
      setEventMethod(syncParams);
    }

    if (actionCfg && actionCfg[afterEvent]) {
      const syncParams = new ts.T_syncParams();
      const _params = Tsrv.utils.clone(params, true);
      _params.from = afterEvent;
      syncParams
        .setApiName(actionCfg[afterEvent])
        .setUserInfo(Tsrv.getUserInfo() as ifs.I_userInfo)
        .setFunInfo(Tsrv.getFunInfo(this.self.mainFunName))
        .setSyncData(_params);
      if (eventType === 'Insert') {
        (target as ts.T_bpaHeadInsRec).setAftEvent(syncParams);
      } else {
        (target as ts.T_ctdUpdRec).setAftEvent(syncParams);
      }
    }
  }

  // 处理组件协调
  public receEventCoordination(
    m: N_oSetupPanel.N_comps.I_eventCoordinationMsg
  ) {
    this.TCoordination.receEventCoordination(m)
      .then(([b, msg]) => {})
      .catch(msg => {
        console.error(msg);
        // this.self.$msg(msg);
      });
  }

  // 处理组件协调
  public sendEventCoordination(
    type: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {
    const r = this.TCoordination.sendEventCoordination(type, this.self.$bus)
      .then(([b, msg]) => {})
      .catch(msg => {
        console.error(msg);
        // this.self.$msg(msg);
      });
  }
}
interface I_cmd extends T_cmd {}

export { I_cmd, T_cmd };
